#!/bin/sh
# This regression test is a part of SIPp.
# A TLS connection that fails its handshake when it is connected again
# after a reset is not taken for reconnected.
. "`dirname "$0"`/../functions"; init

"`get_sipp`" -v | grep -q TLS || skip "no TLS"
command -v openssl >/dev/null || skip "no openssl"

certs=`mktemp -d`
trap 'rm -rf "$certs"' EXIT
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
    -nodes -keyout "$certs/key.pem" -out "$certs/cert.pem" -days 1 \
    -subj /CN=sipp >/dev/null 2>&1 || fail "cannot create the certificate"

tls="-tls_cert $certs/cert.pem -tls_key $certs/key.pem"
sippbg -sn uas -t l1 -i 127.0.0.1 -p 5070 -m 1 $tls
# A proxy to the UAS that resets the UAC's connection after a second,
# then answers its reconnection with bytes that are not TLS.
perl -MIO::Socket::INET -MIO::Select -MTime::HiRes=time -e '
    $l = IO::Socket::INET->new(LocalAddr => "127.0.0.1:5071",
        Listen => 1, ReuseAddr => 1) or die;
    alarm 15;
    $c = $l->accept;
    $u = IO::Socket::INET->new("127.0.0.1:5070") or die;
    $s = IO::Select->new($c, $u);
    for ($end = time + 1; time < $end;) {
        for $h ($s->can_read(0.1)) {
            sysread($h, $b, 65536) and syswrite($h == $c ? $u : $c, $b);
        }
    }
    setsockopt($c, SOL_SOCKET, SO_LINGER, pack("ii", 1, 0));
    close $c;
    $c = $l->accept; syswrite($c, "not TLS\r\n\r\n"); sleep 5' &
sleep 0.2
sippfg -sn uac -t l1 -i 127.0.0.1 -p 5072 -m 2 -r 1 -rp 3000 $tls \
    127.0.0.1:5071 -max_reconnect 1 -reconnect_sleep 100 -timeout 3 \
    -trace_err -error_file "$certs/err.log" >/dev/null 2>&1

if ! grep -q 'Error in SSL' "$certs/err.log"; then
    fail "the reconnection did not fail its handshake"
elif grep -q 'Socket required a reconnection' "$certs/err.log"; then
    fail "a failed handshake taken for a reconnection"
elif ! grep -q 'Could not reconnect TLS socket' "$certs/err.log"; then
    fail "no failed reconnection"
else
    ok
fi
